package com.chiyi.service;

import com.chiyi.bean.TOrder;
import com.chiyi.bean.TProduct;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.util.List;
import java.util.Random;

/**
 * @date 2021/5/13 17:40
 */

@Slf4j
@Service
public class OrderService {

    @Resource
    private ProductClient productClient;
    @Resource
    private RestTemplate restTemplate;
    @Resource
    private DiscoveryClient discoveryClient;
    @Resource
    private RocketMQTemplate rocketMQTemplate;

    @GlobalTransactional
    public TOrder add(Integer pid, Integer uid) {
        TProduct product = productClient.detail(pid);
        // 下订单
        TOrder tOrder = new TOrder();
        tOrder.setNumber(2);
        tOrder.setPname(product.getPname());
        tOrder.setPid(pid);
        tOrder.setUid(uid);
        tOrder.insert();
        int i = new Random().nextInt(10);
        log.info("{}", i);
        if (i % 3 != 0) {
            log.info("主动抛出异常");
            throw new RuntimeException();
        }
        rocketMQTemplate.convertAndSend("order-topic", tOrder);
        return tOrder;

    }

    //获取商品信息
    public TProduct getProductDetail(Integer pid) {
        // 通过 nacos 获取服务对象
        List<ServiceInstance> instances = discoveryClient.getInstances("service-product");
        // 随机获取实例
        int index = new Random().nextInt(instances.size());
        ServiceInstance serviceInstance = instances.get(index);
        // 获取url
        String url = serviceInstance.getHost() + ":" + serviceInstance.getPort();
        log.info("url地址：{}", url);
        TProduct product = restTemplate.getForObject("http://" + url + "/product/detail/" + pid, TProduct.class);
        log.info("商品信息:{}", product);
        return product;

    }

    public List<TProduct> getAllProduct() {
        List<TProduct> tProducts = productClient.getAllProduct();
        log.info("商品信息:{}", tProducts);
        return tProducts;
    }

}
